﻿/*
 
    This file is part of AnkhBG.

    AnkhBG is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AnkhBG is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with AnkhBG.  If not, see <http://www.gnu.org/licenses/>.
 
 */


using System;
using System.Threading;

using Glider.Common.Objects;

namespace AnkhRestart
{
    public class Runner
    {
        Thread thread;

        public Runner()
        {
        }

        ~Runner()
        {
            Stop();
        }

        public void Start()
        {
            thread = new Thread(new ThreadStart(RunThread));
            thread.Start();
        }

        public void Stop()
        {
            if (thread != null)
            {
                thread.Abort();
                thread = null;
            }
        }

        private void RunThread()
        {
            try
            {
                while (Main.Instance.running)
                {
                    if (GContext.Main.IsAttached)
                    {
                        if (GContext.Main.IsGliding == false)
                        {
                            Main.Instance.Window.Log("Found Glider stopped, restarting now.");
                            GContext.Main.StartGlide();
                        }
                    }

                    System.Threading.Thread.Sleep(5000);
                }
            }
            catch (ThreadAbortException) { }
            finally
            {
                if (GContext.Main.IsGliding)
                    GContext.Main.KillAction("AnkhRestart stopped", false);
            }
        }
    }
}